package com.example.ee.progress;

import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.LayerDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    ConstraintLayout    root;
    LayerDrawable       layerDrawable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        root = (ConstraintLayout) findViewById(R.id.root);

        layerDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.progress);
    }

    private void setBackground(){
        int ct = root.getChildCount();
        for (int i = 0 ; i < ct; ++i){
            View view = root.getChildAt(i);
            view.setBackgroundResource(R.drawable.progress);
        }
        getSupportActionBar().setBackgroundDrawable(layerDrawable);
    }

    private int pro;
    private void progressing(){
        int ct = root.getChildCount();
        for (int i = 0; i < ct; ++i){
            View view = root.getChildAt(i);
            LayerDrawable ld = (LayerDrawable) view.getBackground();
            ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(R.id.progressing);
            clipDrawable.setLevel(100 * pro);
        }
        ClipDrawable cd = (ClipDrawable) layerDrawable.findDrawableByLayerId(R.id.progressing);
        cd.setLevel(100 * pro);
    }
    public void onClick(View view){
        final Timer timer = new Timer();
        pro = 0;
        if (view.getId() == R.id.btn_start){
            setBackground();
            TimerTask tt = new TimerTask() {
                @Override
                public void run() {
                    pro += 10;
                    if (pro == 100){
                        timer.cancel();
                    }
                    root.post(new Runnable() {
                        @Override
                        public void run() {
                            progressing();
                        }
                    });
                }
            };
            timer.schedule(tt,1000,1000);
        }
    }
}
